﻿/* Copyright (c) Microsoft Corporation
 * 
 * All rights reserved.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.  You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
 * 
 * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
 * 
 * See the Apache Version 2.0 License for specific language governing permissions and limitations under the License.
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ProximityTapper
{
    [CLSCompliant(false)]
    public class BigEndianConverter
    {
        /// <summary>
        /// Converts 2 bytes from byte array to UInt16 using little endian format
        /// </summary>
        /// <param name="data">Array containing data</param>
        /// <param name="offset">Starting position of the data within an array</param>
        /// <returns></returns>
        public static UInt16 ToUInt16(byte[] data, UInt32 offset)
        {
            UInt16 value = 0;

            // Make sure we have enough bytes to read
            if (sizeof(UInt16) <= (data.Length - offset))
            {
                value = (UInt16)((UInt16)data[offset] << 8);
                offset++;
                value |= (UInt16)data[offset];
            }
            else
            {
                throw new ArgumentOutOfRangeException("Not enough bytes to read");
            }

            return value;
        }

        /// <summary>
        /// Converts 4 bytes from byte array to UInt32 using little endian format
        /// </summary>
        /// <param name="data">Array containing data</param>
        /// <param name="offset">Starting position of the data within an array</param>
        /// <returns></returns>
        public static UInt32 ToUInt32(byte[] data, UInt32 offset)
        {
            UInt32 value = 0;

            // Make sure we have enough bytes to read            
            if (sizeof(UInt32) <= (data.Length - offset))
            {
                value = (UInt32)((UInt32)data[offset] << 24);
                offset++;
                value |= (UInt32)((UInt32)data[offset] << 16);
                offset++;
                value |= (UInt32)((UInt32)data[offset] << 8);
                offset++;
                value |= (UInt32)data[offset];
            }
            else
            {
                throw new ArgumentOutOfRangeException("Not enough bytes to read");
            }

            return value;
        }
    }
}
